// 引入所需的模块
import { createRequire } from 'module'; 
const require = createRequire(import.meta.url);
const https = require('https');

// 设置高德API的参数
const apiKey = 'a7491d2dc122ca2fab5db0b0f8f7ab6f'; // 替换为你的高德API密钥
const location = '南京'; // 替换为你想查询的城市

// 构建高德API的URL

const amapWeatherUrl = `https://restapi.amap.com/v3/weather/weatherInfo?key=${apiKey}&city=${location}`;

// 调用高德API并处理返回的数据
function getWeather() {
  return new Promise((resolve, reject) => {
    https.get(amapWeatherUrl, (res) => {
      let data = '';

      // 监听数据事件
      res.on('data', (chunk) => {
        data += chunk;
      });

      // 监听结束事件
      res.on('end', () => {
        try {
          const weatherData = JSON.parse(data);
          console.log(weatherData);
          if (weatherData.status === '1') {
            resolve(weatherData);
          } else {
            reject(new Error(`获取天气失败：${weatherData.info}`));
          }
        } catch (error) {
          reject(error);
        }
      });
    }).on('error', (err) => {
      reject(err);
    });
  });
}

// 主函数
async function main() {
  try {
    const weather = await getWeather();
    console.log(`当前城市：${weather.lives[0].city}`);
    console.log(`天气：${weather.lives[0].weather}`);
    console.log(`温度：${weather.lives[0].temperature}°C`);
    console.log(`湿度：${weather.lives[0].humidity}`);
    console.log(`风向：${weather.lives[0].winddirection}`);
    console.log(`风力：${weather.lives[0].windpower}`);
  } catch (error) {
    console.error(error.message);
  }
}

main();
